<template>
  <div>
    <!-- 页面,面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- cart的白色背景 -->
    <el-card class="box-card">
      <el-alert title="警告提示的文案" type="info" center show-icon>
      </el-alert>
      <el-steps :space="200" :active="step_index" align-center
                finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab 标签页 ul>li -->
      <el-form label-position="top" ref="addFormRef" :model="addForm"
               :rules="rules" label-width="80px" class="demo-ruleForm">
        <el-tabs :before-leave='beforeLeave' tab-position="left"
                 v-model="activeName" @tab-click='tabClick'>
          <el-tab-pane label="基本信息" name='0'>
            <el-form-item label="商品名称" prop="goods_name" la>
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="options"
                           :props='cateProps' @change="cascaderChg">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name='1'>
            <el-form-item :label='item.attr_name' v-for="item in cateDate"
                          :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label='val'
                             v-for="(val,i) in item.attr_vals" :key="i">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name='2'>
            <el-form-item :label='item.attr_name' v-for="item in onlyDate"
                          :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3'>
            <!-- upload组件,会自己去访问后台,并没有用到axios,会用自带的方法去访问后台 -->
            <el-upload class="upload-demo" :action="uploadUrl"
                       :on-success="handleSuccess" :headers='headerObj'
                       :on-preview="handlePreview" :on-remove="handleRemove"
                       list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4'>
            <!-- 加载编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce" />
            <el-button type="primary" @click="add_good">保存商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 动态参数dielog -->
    <el-dialog title="图片预览" class="mydialog" :visible.sync="dialogImgVisible">
      <img :src="img_src" alt="上传的图片" srcset="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  mounted () {
    this.getCateList();
  },
  data () {
    return {
      dialogImgVisible: false,
      // 图片路径
      img_src: '',
      // 上传组件的头部
      headerObj: { Authorization: window.sessionStorage.getItem("token") },
      // 上传图片的路径
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 静态属性
      onlyDate: [],
      // 动态参数
      cateDate: [],
      // checkList: [],
      // 配置渲染的字段
      cateProps: {
        // 改为false必须选择子节点
        checkStrictly: false,
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      options: [],
      selectVal: [],
      // 商品的添加类
      addForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 保存的是上传图片的路径
        pics: [],
        // 编辑器的内容
        goods_introduce: "",
      },
      // 校验规则
      rules: {
        goods_name: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
        ]
      },
      step_index: 0,
      activeName: '0'
    }
  },
  methods: {
    add_good () {
      console.log(this.addForm)
      // 校验from表单没有问题
      this.$refs.addFormRef.validate(async (valid) => {
        // 数据有错
        if (!valid) {
          return this.$message.error('请填写正确的数据')
        }
        // react 的时候学 拷贝出来新的对象,是浅拷贝
        const form = { ...this.addForm, goods_cat: this.addForm.goods_cat.join(",") }
        // this.addForm.goods_cat = this.addForm.goods_cat.join(",")
        const attrs = [];
        this.onlyDate.forEach((item) => {
          attrs.push({ attr_id: item.attr_id, attr_vals: item.attr_vals })
        })
        this.cateDate.forEach((item) => {
          attrs.push({ attr_id: item.attr_id, attr_vals: item.attr_vals.join(" ") })
        })
        form.attrs = attrs
        // 数据通过校验
        const { data: { data, meta } } = await this.$axios.post('goods', form)
        console.log(data, meta)
        if (meta.status !== 201) {
          return this.$message.error("创建商品失败了")
        }
        this.$router.push('/goods')
      })
    },
    // 上传成功时的回调方法
    handleSuccess (response) {
      const { data, meta } = response
      if (meta.status !== 200) {
        return this.$message.error('失败了')
      }
      this.addForm.pics.push({ pic: data.tmp_path })
      console.log(this.addForm)
    },
    /* 图片上传的方法 */
    handlePreview (file) {
      // url是图片的绝对路径,磁盘符开头,E:,网站开头
      // http://127.0.0.1:8888/tmp_uploads\\d1dcabc04aa885b537d7b5a85657da08.png
      // https://static-cdn-oss.mosoteach.cn/mssvc/icons/icon_cc_cover1_b@2x.png
      console.log(file)
      this.img_src = file.response.data.url;
      this.dialogImgVisible = true;
    },
    // 删除图片的方法
    handleRemove (file) {
      console.log(file)
      console.log(this.addForm.pics)
      // 删除数组数据方法()需要下标
      // pop,shift,splice
      // findIndex 查找元素下标
      // indexOf num,str,, 对对象和数组不行,传值和传址的区别了
      // findIndex 专门的判断对象的
      const i = this.addForm.pics.findIndex((item) => {
        return item.pic === file.response.data.tmp_path
      })
      this.addForm.pics.splice(i, 1)
    },
    // 三级联动改变校验
    cascaderChg () {
      // 如果不是3级分类不让选
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        return this.$message.error('请选择第3级的分类')
      }
    },
    // 切换的校验方法
    beforeLeave (newName, oldName) {
      if (oldName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类")
        return false
      }
      console.log('将要进入的', newName, '将要离开的', oldName)
      // return false
    },
    // 获取三级联动的数据
    async getCateList () {
      const { data: { data, meta } } = await this.$axios.get('categories')
      console.log(data, meta)
      if (meta.status !== 200) {
        return this.$message.error('获取参数信息失败')
      }
      this.options = data
    },
    // tab的实例
    async tabClick (tab) {
      // 将字符串转化成数字 Number.parseInt,tab.index -0,+tab.index
      // console.log(tab.index,this.activeName)
      // 步骤,应该是激活的标签页的名字
      this.step_index = +this.activeName
      if (this.step_index === 1) {
        console.log(this.addForm.goods_cat[2])
        const { data: { data, meta } } = await this.$axios.get(`categories/${this.addForm.goods_cat[2]}/attributes`, { params: { sel: 'many' } })
        if (meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }
        // 修改data里边的数据
        data.forEach((item) => {
          item.attr_vals = item.attr_vals === "" ? [] : item.attr_vals.split(" ")
        })
        this.cateDate = data
        console.log(data)
      }
      // 判断是否到属性页面
      if (this.step_index === 2) {
        console.log(this.addForm.goods_cat[2])
        const { data: { data, meta } } = await this.$axios.get(`categories/${this.addForm.goods_cat[2]}/attributes`, { params: { sel: 'only' } })
        if (meta.status !== 200) {
          return this.$message.error('获取商品属性失败')
        }
        // 修改data里边的数据
        this.onlyDate = data
        console.log(data)
      }
    },
  }
}
</script>

<style lang="css" scoped>
.el-tabs,
el-tab-pane {
  height: 100%;
}
.el-form {
  text-align: left;
}
</style>